<template>
  <div class="site-chart-box-main">
    <van-nav-bar safe-area-inset-top placeholder :title="siteName" left-arrow fixed @click-left="onClickLeft" />
    <van-pull-refresh v-model="isLoading" :pulling-text="$t('PullingText')" :loosing-text="$t('PullingText')" :success-text="$t('refreshSuccee')" @refresh="onRefresh">
      <div id="powerChart" name="second" ></div>
      <div class="tabs-check-box">
          <div class="tabs-child" @click='yieldNameCode = 1;switchChart(1,chartDatas)' :class="yieldNameCode==1?'active':''">{{$t('Yield')}}</div>
          <div class="tabs-child" @click='yieldNameCode = 2;switchChart(2,chartDatas)' :class="yieldNameCode==2?'active':''">{{$t('ConsumeEnergy')}}</div>
      </div>
      <div class="selectBox">
        <!-- 年月日 -->
        <div class="sel" @click="showPicker2 = true">{{timeName}}</div>
        <van-popup v-model="showPicker2" round position="bottom">
          <van-picker
            show-toolbar
            :columns="columns2"
            @cancel="showPicker2 = false"
            @confirm="onConfirm2"
            :confirm-button-text="$t('OK')"
            :cancel-button-text="$t('Cancel')"
          />
        </van-popup>
        <!-- 年月选择框 -->
        <div class="sel" @click="showPicker3 = true" v-if="timeName==$t('Month')">{{timeVal}}</div>
        <van-popup v-model="showPicker3" round position="bottom">
          <van-datetime-picker
            v-model="currentDate"
            type="year-month"
            @cancel="showPicker3 = false"
            @confirm="onConfirm3"
            :confirm-button-text="$t('OK')"
            :cancel-button-text="$t('Cancel')"
          />
        </van-popup>
        <!-- 年选择框 -->
        <div class="sel" @click="showPicker4 = true" v-if="timeName==$t('Year')">{{value4}}</div>
        <van-popup v-model="showPicker4" round position="bottom">
          <van-picker
            show-toolbar
            :columns="columns4"
            @cancel="showPicker4 = false"
            @confirm="onConfirm4"
            :confirm-button-text="$t('OK')"
            :cancel-button-text="$t('Cancel')"
          />
        </van-popup>
      </div>
      <div id="myChart"></div>
    </van-pull-refresh>
  </div>
</template>

<script>
import moment from 'moment'
export default {
  data(){
    return {
      siteName:localStorage.getItem('siteName'),
      isLoading:false,
      yieldNameCode:1,
      timeName: this.$t('Month'),
      timeNameCode:2,
      value4:(new Date()).getFullYear(),
      showPicker2: false,
      showPicker3: false,
      showPicker4: false,
      columns2: [this.$t('Month'), this.$t('Year'),this.$t('AllYear')],
      currentDate:new Date(),
      timeVal:moment(new Date()).format('YYYY/MM'),
      columns4:this.getYear(),
      dataCurrent:[moment(new Date()).format('YYYY'),moment(new Date()).format('MM')],
      chartDatas:'',
      BarChart:'',
      fifteenRefresh:null
    }
  },
  methods: {
    onClickLeft(){
      this.$router.push({path:'/main/sitedetail'});
    },
    onConfirm2(value,index) {
      this.timeName = value;
      this.showPicker2 = false;
      if(index==0){
        this.dataCurrent=this.timeVal.split("/");
      }else if(index==1){
        this.dataCurrent=[this.value4,moment(new Date()).format('MM')];
      }else if(index==2){
        this.dataCurrent=[moment(new Date()).format('YYYY'),moment(new Date()).format('MM')];
      }
      this.timeNameCode=index+2;
      this.getYielCharts(this.timeNameCode,...this.dataCurrent,this.yieldNameCode);
    },
    onConfirm3(value) {
      this.showPicker3 = false;
      this.timeVal=moment(value).format('YYYY/MM');
      this.dataCurrent=this.timeVal.split("/");
      this.getYielCharts(this.timeNameCode,...this.dataCurrent,this.yieldNameCode);
    },
    onConfirm4(value) {
      this.showPicker4 = false;
      this.value4 = value;
      this.dataCurrent=[this.value4,moment(new Date()).format('MM')];
      this.getYielCharts(this.timeNameCode,...this.dataCurrent,this.yieldNameCode);
    },
    getYear(){
      let years=(new Date()).getFullYear()-2017;
      let yearsArr=[];
      for(let i=0;i<=years;i++){
        yearsArr.push(2017+i);
      }
      return yearsArr;
    },
    async getYielCharts(reportType,year,month,hover){
      this.comm.loadingShow();
      let data=await this.API.siteYieldCharts(localStorage.getItem('domain'),
        {'reportType':reportType,
        'siteId':localStorage.getItem('siteId'),
        'tokenId':localStorage.getItem('tokenId'),
        'year':year,
        'month':month,
        'webTime':moment(new Date()).format('YYYY,MM,DD')
        });
      if((data.success)&&data.result!==null){
        this.chartDatas=data;
        this.switchChart(hover,this.chartDatas)
      }
    },
    switchChart(hover,data){
      if(hover==1){
        let [times,y1,y2,y3]=[[],[],[],[]];
        for(let i= 0;i<data.result.length;i++){
          times.push(data.result[i].time);//横坐标
          if(data.result[i].feedinenergy==null||data.result[i].feedinenergy==undefined){
            data.result[i].feedinenergy=0;
          }
          if(data.result[i].yieldtoday==null||data.result[i].yieldtoday==undefined){
            data.result[i].yieldtoday=0;
          }
          if(data.result[i].epsEnergy==null||data.result[i].epsEnergy==undefined){
            data.result[i].epsEnergy=0;
          }
          if(data.result[i].feedinenergy>data.result[i].yieldtoday){
            data.result[i].feedinenergy=data.result[i].yieldtoday;
          }
          let selfUse=data.result[i].yieldtoday-data.result[i].feedinenergy;
          y1.push((data.result[i].feedinenergy).toFixed(2));
          y2.push(selfUse.toFixed(2));
          y3.push((data.result[i].epsEnergy).toFixed(2));
        }
        let legend=[this.$t('FeedInEnergy'),this.$t('SelfUse'),this.$t('EPSEnergy')];
        let color=['#F4B600','#6DA719','#9E7525'];
        let series=[
          {name: legend[0],type: 'bar',stack: legend[2],data: y1},
          {name: legend[1],type: 'bar',stack: legend[2],data: y2},
          {name: legend[2],type: 'bar',stack: legend[2],data: y3}
        ];
        this.$nextTick(()=>{
          this.BarChart=this.commChart.barChart('myChart',color,this.timeNameCode,times,legend,series);
        })
      }else{
        let [times2,y3,y4,y5]=[[],[],[],[]];
        for(let i1= 0;i1<data.result.length;i1++){
          times2.push(data.result[i1].time);//横坐标
          if(data.result[i1].consumeenergy==null||data.result[i1].consumeenergy==undefined){
            data.result[i1].consumeenergy=0;
          }
          if(data.result[i1].yieldtoday==null||data.result[i1].yieldtoday==undefined){
            data.result[i1].yieldtoday=0;
          }
          if(data.result[i1].epsEnergy==null||data.result[i1].epsEnergy==undefined){
            data.result[i1].epsEnergy=0;
          }
          y3.push((data.result[i1].consumeenergy).toFixed(2));
          if(data.result[i1].feedinenergy>data.result[i1].yieldtoday){
            data.result[i1].feedinenergy=data.result[i1].yieldtoday;
          }
          var selfUse1=data.result[i1].yieldtoday-data.result[i1].feedinenergy;
          y4.push(selfUse1.toFixed(2));
          y5.push((data.result[i1].epsEnergy).toFixed(2));
        }
        let color=['#EB6206','#6DA719','#9E7525'];
        let legend=[this.$t('ConsumeEnergy'),this.$t('SelfUse'),this.$t('EPSEnergy')];
        let series=[
          {name: legend[0],type: 'bar',stack: legend[2],data: y3},
          {name: legend[1],type: 'bar',stack: legend[2],data: y4},
          {name: legend[2],type: 'bar',stack: legend[2],data: y5}
        ];
        this.$nextTick(()=>{
          this.BarChart=this.commChart.barChart('myChart',color,this.timeNameCode,times2,legend,series);
        })
      }
    },
    //获取功率
    async getPowerCharts(){
      this.comm.loadingShow();
      let data=await this.API.homePowerCharts(localStorage.getItem('domain'),
        {'tokenId':localStorage.getItem('tokenId'),
        'siteId':localStorage.getItem('siteId'),
        'time':moment(new Date()).format('YYYY-MM-DD')
        });
      let [times,pv,ac,load,grid,eps,BatteryPower,BatteryCapacity]=[[],[],[],[],[],[],[],[]];
      for(let i= 0;i<data.length;i++){
        let arrs=(data[i].uploadTimeValue).split(' ');
        arrs=arrs[arrs.length-1];
        arrs=arrs.split(":");
        arrs=arrs.slice(0,2);
        arrs=arrs.join(":");
        times.push(arrs);
        pv.push(((data[i].powerdc1||0)+(data[i].powerdc2||0)+(data[i].powerdc3||0)+(data[i].powerdc4||0)).toFixed(1));
        ac.push((data[i].gridpower||0).toFixed(1));
        load.push((data[i].relayPower||0).toFixed(1));
        grid.push((data[i].feedinpower||0).toFixed(1));
        eps.push((data[i].epspower||0).toFixed(1));
        BatteryPower.push((data[i].batPower1||0).toFixed(1));
        BatteryCapacity.push((data[i].batteryCapacity||0).toFixed(1));
      }
      let legend=[this.$t('PVPower')+' (W)', this.$t('ACPower')+' (W)', this.$t('LoadPower')+' (W)', this.$t('GridPower')+' (W)',this.$t('EPSPower')+' (W)',this.$t('BatteryPower')+' (W)',this.$t('BatteryCapacity')+' (%)',this.$t('EVCharger')+' (W)'];
      let series=[
        {name: legend[0],type: 'line',symbol: 'none',smooth: true,itemStyle: {normal: {color: '#F4B600'}},data: pv},
        {name: legend[1],type: 'line',smooth: true,symbol: 'none',itemStyle: {normal: {color: '#72BC38'}},data: ac},
        {name: legend[2],type: 'line',smooth: true,symbol: 'none',itemStyle: {normal: {color: '#C962F7'}},data: load},
        {name: legend[3],type: 'line',smooth: true,symbol: 'none',itemStyle: {normal: {color: '#EB6206'}},data: grid},
        {name: legend[4],type: 'line',smooth: true,symbol: 'none',itemStyle: {normal: {color: '#B97A57'}},data: eps},
        {name: legend[5],type: 'line',smooth: true,symbol: 'none',itemStyle: {normal: {color: '#2C5F05'}},data: BatteryPower},
        {name: legend[6],type: 'line',smooth: true,symbol: 'none',itemStyle: {normal: {color: '#0AAAA0'}},data: BatteryCapacity}
      ];
      this.commChart.lineChart3('powerChart',times,legend,series);
    },
    onRefresh(){
      this.isLoading=false;
      this.getYielCharts(this.timeNameCode,...this.dataCurrent,this.yieldNameCode);
      this.getPowerCharts();
    },
  },
  mounted(){
    this.getYielCharts(2,...this.dataCurrent,1);
    this.getPowerCharts();
    this.fifteenRefresh=setInterval(()=>{
      this.getYielCharts(this.timeNameCode,...this.dataCurrent,this.yieldNameCode);
      this.getPowerCharts();
    },900000);
  },
  destroyed(){
    clearInterval(this.fifteenRefresh);
    this.fifteenRefresh=null;
  }
}
</script>

<style scoped lang="less">
.site-chart-box-main{
  .tabs-check-box{
    width: 85%;
    display: flex;
    margin: 0 auto;
    background-color: #ccc;
    justify-content: space-around;
    border-radius: 15px;
    overflow: hidden;
    .tabs-child{
      flex: 1;
      padding: 10px 5px;
    }
    .active{
      background-color: #3B3D4E;
      color: #fff;
    }
  }
}
.van-hairline--bottom::after{
  border: none;
}
.selectBox{
  width: 100%;
  display:flex;
  padding: 20px 0 10px 0;
}
#powerChart{
  width: 100%;
  height: 280px;
  margin-top: 15px;
}
#myChart{
  width: 100%;
  height: 280px;
  margin: 15px 0;
}
</style>
